package com.ws.server.formal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

public class WebSocketHandler extends ChannelInboundHandlerAdapter{
	private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketHandler.class);
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		if (msg instanceof WebSocketFrame) {
			// websocket业务处理
			handleWebSocketRequest(ctx, (WebSocketFrame)msg);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		ctx.close();
	}
	
	private void handleWebSocketRequest(ChannelHandlerContext ctx, WebSocketFrame req) throws Exception {
		if (req instanceof CloseWebSocketFrame) {
			// 关闭websocket连接
			return;
		}
		if (req instanceof PingWebSocketFrame) {
			ctx.channel().write(new PongWebSocketFrame(req.content().retain()));
			return;
		}
		if (!(req instanceof TextWebSocketFrame)) {
			throw new UnsupportedOperationException("当前只支持文本消息，不支持二进制消息");
		}
		ctx.channel().writeAndFlush(new TextWebSocketFrame(((TextWebSocketFrame)req).text()));
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Recieve and send msg:{} to {}", ((TextWebSocketFrame)req).text(), ctx.channel().remoteAddress());
		}
	}

}